<?php
namespace App\Repositories\Egress;

use App\Exceptions\API\APIException;
use App\Exceptions\API\BadRequest;
use App\Models\Egress;

class EgressDBRepository implements EgressRepository
{

    public function getPaginator(EgressFilter $egressFilter)
    {
        $query = $this->getDBQuery($egressFilter);

        return $query->paginate($egressFilter->getPerPage());
    }

    protected function getDBQuery(EgressFilter $egressFilter)
    {
        $EgressQuery = Egress::query();
        $EgressQuery->with('users.department');

        if ($userId = $egressFilter->getUserId()) {
            $egressFilter->where('user_id', $userId);
        }

        if ($name = $egressFilter->getName()) {
            $EgressQuery->whereHas('users' , function ($query) use($name) {
                $query->where('name', 'like', '%'.$name.'%');
            });
        }

        if ($departmentName = $egressFilter->getDepartmentName()) {
            $EgressQuery->whereHas('users.department' , function ($query) use($departmentName) {
                $query->where('name', 'like', '%'.$departmentName.'%');
            });
        }

        $startTime = $egressFilter->getStartTime();
        $endTime = $egressFilter->getEndTime();
        if($startTime && $endTime){
            $egressFilter->where('dates','>=',$startTime)
                ->where('dates','<=',$endTime);
        }

        return $EgressQuery;
    }

}
